package com.icode.gulimall.product.service.impl;

import com.icode.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.icode.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.icode.gulimall.product.entity.AttrEntity;
import com.icode.gulimall.product.entity.ProductAttrValueEntity;
import com.icode.gulimall.product.service.AttrAttrgroupRelationService;
import com.icode.gulimall.product.service.AttrService;
import com.icode.gulimall.product.service.ProductAttrValueService;
import com.icode.gulimall.product.vo.Attr;
import com.icode.gulimall.product.vo.AttrGroupWithAttrsVo;
import com.icode.gulimall.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icode.common.utils.PageUtils;
import com.icode.common.utils.Query;

import com.icode.gulimall.product.dao.AttrGroupDao;
import com.icode.gulimall.product.entity.AttrGroupEntity;
import com.icode.gulimall.product.service.AttrGroupService;
import org.springframework.util.StringUtils;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrAttrgroupRelationService relationService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //1、获取key
        String key = (String) params.get("key");
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isEmpty(key)) {
            wrapper.eq("brand_id", key).or().like("brand_name", key);
        }
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        String key = (String) params.get("key");
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>();
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(attrGroupEntityQueryWrapper -> {
                attrGroupEntityQueryWrapper.eq("attr_group_id", key).or().like("attr_group_name", key);
            });
        }
        if (catelogId == 0) {
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    wrapper);
            return new PageUtils(page);
        } else {
            wrapper.eq("catelog_Id", catelogId);
            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params), wrapper);
            return new PageUtils(page);
        }

    }

    @Override
    public List<AttrGroupWithAttrsVo> getAllAttrs(Long catelogId) {
        //获得此分类下的所有分组
        List<AttrGroupEntity> attrGroupEntities = this.baseMapper.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));

        List<AttrGroupWithAttrsVo> collect = attrGroupEntities.stream().map((attrGroup) -> {
            //将分组信息复制到vo中
            AttrGroupWithAttrsVo withAttrsVo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(attrGroup, withAttrsVo);

//            List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
//                    .eq("attr_group_id", withAttrsVo.getAttrGroupId())
//            );
//            List<AttrEntity> attrs = relationEntities.stream().map((attrRelation) -> {
//                return attrService.getById(attrRelation.getAttrId());
//            }).collect(Collectors.toList());

            List<AttrEntity> attrs = attrService.getRelationAttr(withAttrsVo.getAttrGroupId());
            withAttrsVo.setAttrs(attrs);
            return withAttrsVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 查出当前属性所有的分组信息和当前spu下的所有值
     *
     * @param spuId
     * @param catalog
     * @return
     */
    @Override
    public List<SpuItemAttrGroupVo> getAttrGroupWithAttrsBySpuId(Long spuId, Long catalog) {
        List<AttrGroupEntity> groupEntities = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catalog));
        Map<Long, Attr> attrMap = productAttrValueService.getAttrBySpuId(spuId).stream().collect(Collectors.toMap(ProductAttrValueEntity::getAttrId, attrVal ->
                new Attr(attrVal.getAttrId(), attrVal.getAttrName(), attrVal.getAttrValue())
        ));

        List<SpuItemAttrGroupVo> collect = groupEntities.stream().map(item -> {
            //操作每一个属性分组
            SpuItemAttrGroupVo spuItemAttrGroupVo = new SpuItemAttrGroupVo();
            spuItemAttrGroupVo.setGroupName(item.getAttrGroupName());
            List<Attr> attrList = new ArrayList<>();
            relationService.list(
                    //查询分组下的所有属Id
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", item.getAttrGroupId()))
                    .stream().map(r -> r.getAttrId()).collect(Collectors.toList())
                    //将相关的属性封装到attr中
                    .stream().forEach(r -> {
                if (attrMap.containsKey(r))
                    attrList.add(attrMap.get(r));

            });
            spuItemAttrGroupVo.setAttrs(attrList);
            return spuItemAttrGroupVo;
        }).collect(Collectors.toList());
        return collect;
    }


}